<template>
  <a-layout id="components-layout-demo-custom-trigger">
<!--    导航区-->
    <a-layout-sider width="256px" v-model="collapsed" :trigger="null" collapsible>
<!--      logo-->
      <div class="logo">
        <a class="logo-link" href="javascript:void(0)" title="资源共享平台">
          <img class="logo-img" src="../../assets/logo3.png" width="32px" height="32px"/>
          <h1 class="logo-title">
            资源共享平台
          </h1>
        </a>
      </div>
<!--      菜单区-->
      <a-menu theme="dark"
              @openChange="onOpenChange"
              @select="selectHandler"
              :open-keys="openKeys"
              :selected-keys="selectKeys"
              mode="inline">
        <a-sub-menu v-for="item in menus.menuList" :key="item.id">
<!--          父级图标-->
          <span slot="title"><a-icon :type="item.icon"/>
            <span>{{item.title}}</span>
          </span>
          <a-menu-item v-for="subitem in item.children" @click="clickMenu(subitem.href)" :key="subitem.href">
<!--            子菜单图标-->
            <a-icon :type="subitem.icon" />
            {{subitem.title}}
          </a-menu-item>
        </a-sub-menu>
      </a-menu>
    </a-layout-sider>
    <a-layout>
<!--      右侧头部-->
      <a-layout-header style="background: #fff; padding: 0">
        <div class="header-all">
          <span class="header-all-left">
            <a-icon
                class="trigger"
                :type="collapsed ? 'menu-unfold' : 'menu-fold'"
                @click="() => (collapsed = !collapsed)"
            />
          </span>
          <div class="header-all-right"
               :class="{headerAllRightStyle:isEnterUserInfo}"
               @mouseenter="isEnterUserInfo = true"
               @mouseleave="isEnterUserInfo = false">
            <span class="header-all-right-user cursor">
              <a-avatar :src="$store.state.user.loginUser.avator" style="margin-right: 5px" />
              <span style="margin-right: 5px">{{$store.state.user.loginUser.loginName}}</span>
              <a-tag v-if="$store.state.user.loginUser.type === 1" color="blue">超级管理员</a-tag>
              <a-tag v-else-if="$store.state.user.loginUser.type === 2" color="cyan">管理员</a-tag>
              <a-tag v-else>普通用户</a-tag>
            </span>
<!--            鼠标移入显示-->
            <ul v-show="isEnterUserInfo" class="header-all-right-swag">
              <a-button class="swag-item" type="link" @click="userItemClickHandler('info')">个人中心</a-button>
              <a-button class="swag-item" type="link" @click="userItemClickHandler('settings')">个人设置</a-button>
              <a-button class="swag-item" type="link" @click="userItemClickHandler('upassword')">修改密码</a-button>
              <a-button class="swag-item" type="link" @click="logOutHandler">退出系统</a-button>
              <a-modal
                  title="退出系统"
                  :visible="visible"
                  :confirm-loading="confirmLoading"
                  cancelText="取消"
                  okText="确认"
                  @ok="handleOk"
                  @cancel="handleCancel"
              >
                <p>确认退出系统吗?</p>
              </a-modal>

<!--              修改密码-->
              <a-modal
                  :title="ModalText"
                  :visible="passVisible"
                  :confirm-loading="passConfirmLoading"
                  okText="确认修改"
                  cancelText="保持原样"
                  @ok="passHandleOk"
                  @cancel="passHandleCancel"
              >
                <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }">
                  <a-form-item label="旧密码">
                    <a-input-password
                        v-decorator="['oldPwd', {
                          rules: [
                              { required: true, message: '请输入旧密码' },
                              { validator: checkOldPwdHandler }],validateTrigger: ['blur'] }]"
                    />
                  </a-form-item>
                  <a-form-item label="新密码">
                    <a-input-password
                        v-decorator="['pwd', {
                          rules: [
                              { required: true, message: '请输入新密码' },
                              { validator: handlePassword }],validateTrigger: ['change', 'blur'] }]"
                    />
                  </a-form-item>
                  <a-form-item label="确认密码">
                    <a-input-password
                        v-decorator="['pwd2', {
                          rules: [
                              { required: true, message: '请确认新密码' },
                              { validator: handlePwd2Check }],validateTrigger: ['change', 'blur'] }]"
                    />
                  </a-form-item>
                </a-form>
              </a-modal>
            </ul>
          </div>
        </div>
      </a-layout-header>
<!--      内容去-->
      <div
          :style="{ margin: '24px 16px', padding: '24px', background: '#fff'}">

        <router-view></router-view>
      </div>
    </a-layout>
  </a-layout>
</template>
<script>

import {mapState} from "vuex";
import {checkOldPassword, updatePassword,getMenuList} from "@/api/user";
import { getAnnoCommendInfo,knownAnno } from '@/api/sys'
export default {
  name: "Index",
  data() {
    return {
      isEnterUserInfo:false,
      collapsed: false,
      // 退出确认框
      visible: false,
      confirmLoading: false,
      rootSubmenuKeys: [],
      openKeys: [],
      selectKeys:[],
      // 修改密码
      passVisible: false,
      passConfirmLoading: false,
      formLayout: 'horizontal',
      user:{},
      routersList:[],
      form: this.$form.createForm(this, { name: 'coordinated' }),
    };
  },
  watch:{
    $route:{
      immediate:true,
      handler:function(newValue){
        let path = newValue.meta.path
        const menus = this.menuList;
        // 路由跳转后菜单和路径保持一致
        if (menus && menus.length > 0){
          let opens = [];
          menus.forEach(menu => {
            let child = menu.children;
            if (child){
              child.forEach((c) => {
                if (c.href === path){
                  opens.push(menu.id);
                }
              })
            }
          })
          if (opens && opens.length > 0){
            this.openKeys = opens;
          }
        }
        if (path){
          this.$nextTick(() => {
            this.selectKeys = [path];
          })
        }
      }
    },
    // 监视菜单数据
    menus : {
      immediate:true,
      handler:function(newValue){
        if (!newValue.menuList){
          this.$store.dispatch('getMenuList');
        }
        // 刷新页面后选中的默认展开
        if (newValue.menuList){
          let ids = newValue.menuList.map(m => m.id + '');
          this.$nextTick(() => {
            this.rootSubmenuKeys = ids;
            const path = this.$route.path;
            let opens = [];
            this.menuList.forEach(menu => {
              let child = menu.children;
              if (child){
                 child.forEach((c) => {
                  if (c.href === path){
                    opens.push(menu.id);
                  }
                })
              }
            })
            if (opens && opens.length > 0){
              this.openKeys = opens;
            }
          })
        }
      }
    }
  },
  created() {
    // 获取用户信息
    if (!this.$store.state.user.loginUser.userName){
      this.$store.dispatch('getUserInfo')
    }
  },
  mounted() {
    this.initLogPreInfo();
    this.user = this.$store.state.user.loginUser;
    // 加载公告信息
    this.loadAccoInfo();
    // 路由菜单默认展开
    this.routeMenuHandler();
  },
  computed: {
    ...mapState({
      menus: state => state.permission.menuRouters,
      menuList: state => state.permission.menuList,
    }),

    ModalText(){
      return "修改用户 " + this.user.loginName + " 的密码"
    }
  },
  methods:{
    // 刷新后路由父菜单默认展开
    routeMenuHandler(){
      const routers = this.$store.state.permission.menuList;
    },
    // 加载日志前置信息
    initLogPreInfo(){
      this.$store.dispatch('logPreInfo');
    },
    // 加载公告信息
    async loadAccoInfo(){
      const {code, data} = await getAnnoCommendInfo();
      if (code === 200){
        let result = new Array();
        const h = this.$createElement;
        // 标题
        result.push(h('h2','标题: ' + data.annoTitle));
        result.push(h('h2','发布时间: ' + this.$moment(data.annoPublishTime).format('yyyy-MM-DD HH:mm:ss')));
        result.push(h('h2','发布人: ' + data.user.userName));
        result.push(h('h2','公告内容: '));
        if (data.annoContentList && data.annoContentList.length > 0){
          data.annoContentList.forEach(c => {
            result.push(h('h3',c));
          })
        }
        this.$success({
          title: '系统公告',
          width:'600px',
          content: h('div', {}, result),
          okText: '我知道了',
          onOk () {
            knownAnno(data.id);
          }
        });
      }
    },
    // 点击了菜单
    clickMenu(url){
      this.$router.push(url)
    },
    // 退出确认框
    logOutHandler() {
      this.visible = true;
    },
    // 确认退出
    handleOk() {
      this.confirmLoading = true;
      setTimeout(() => {
        this.visible = false;
        this.confirmLoading = false;
        this.$store.dispatch('logout');
      }, 2000);
    },
    // 取消退出
    handleCancel() {
      this.visible = false;
    },
    // 鼠标离开用户头像
    userItemClickHandler(r){
      if (r === 'info'){
        this.$router.push("/admin/myinfo")
      } else if(r === 'settings'){
        this.$router.push({name:'settings'})
      } else if (r === 'upassword'){
        this.passVisible = true;
      }
    },

    // 打开时的回调
    onOpenChange(openKeys) {
      // 手风琴模式，只打开一个
      let latestOpenKey = openKeys[openKeys.length - 1];
      if (latestOpenKey){
        this.openKeys = [latestOpenKey];
      } else {
        this.openKeys = [];
      }
    },

    // 选中使得回调
    selectHandler(recode){
      this.selectKeys = recode.selectedKeys;
    },
    // 旧密码校验
    checkOldPwdHandler(rule, value, callback){
      const {user} = this;
      if (value === '' || value === undefined) {
        return callback()
      } else{
        const password = this.form.getFieldValue('oldPwd')
        let params = {pwd: password, userId:user.userId};
        checkOldPassword(params).then(res => {
          const { code } = res;
          if (code === 200){
            callback();
          } else {
            callback(new Error('旧密码错误'));
          }
        }).catch(() => {
          this.$message.error('请求发送失败');
        })
      }
    },
    // 密码安全校验
    handlePassword (rule, value, callback) {
      if (value.length > 1 && value.length < 6){
        callback(new Error('密码强度太低'))
      }else{
        callback();
      }
    },
    // 确认密码校验
    handlePwd2Check (rule, value, callback) {
      const password = this.form.getFieldValue('pwd')
      if (value && password && value.trim() !== password.trim()) {
        callback(new Error('两次密码不一致'))
      }
      callback()
    },
    // 修改密码
    passHandleOk(e) {
      const _this = this;
      const { user } = this;
      e.preventDefault();
      this.passConfirmLoading = true;
      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          let params = {...values, userId: user.userId,};
          updatePassword(params).then((res) => {
            const {code,data,msg} = res;
            if (code === 200){
              _this.$message.success(msg);
              _this.form.resetFields();
              setTimeout(() => {
                _this.passVisible = false;
                _this.passConfirmLoading = false;
              }, 1000);
            } else if(code === 400){
              _this.$message.error(msg);
            } else {
              _this.$message.error(msg);
              setTimeout(() => {
                _this.passVisible = false;
                _this.passConfirmLoading = false;
              }, 1000);
            }
          }).catch((error) => {
            _this.$message.error('网络异常');
            setTimeout(() => {
              _this.passVisible = false;
              _this.passConfirmLoading = false;
            }, 1000);
          })
          _this.passConfirmLoading = false;
        } else {
          _this.passConfirmLoading = false;
        }
      });
    },
    passHandleCancel(e) {
      this.passVisible = false;
      this.form.resetFields();
    }
  }
}
</script>

<style scoped>
#components-layout-demo-custom-trigger{
  height: 100vh;
}
#components-layout-demo-custom-trigger .trigger {
  font-size: 18px;
  line-height: 64px;
  padding: 0 24px;
  cursor: pointer;
  transition: color 0.3s;
}

#components-layout-demo-custom-trigger .trigger:hover {
  color: #1890ff;
}

#components-layout-demo-custom-trigger .logo {
  position: relative;
  height: 64px;
  padding-left: 24px;
  overflow: hidden;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
  line-height: 64px;
  background: #001529;
}

#components-layout-demo-custom-trigger .logo .logo-link{

}

#components-layout-demo-custom-trigger .logo .logo-link .logo-title{
  color: #fff;
  font-size: 20px;
  margin: 0 0 0 12px;
  font-family: Avenir, Helvetica Neue, Arial, Helvetica, sans-serif;
  font-weight: 600;
  vertical-align: middle;
  display: inline-block;
}

.header-all{
  position: relative;
  height: 64px;
  padding: 0;
  background: #fff;
  -webkit-box-shadow: 0 1px 4px #cccccc;
  box-shadow: 0 1px 4px #cccccc;
}

.header-all .header-all-left{
  height: 64px;
  line-height: 64px;
  vertical-align: top;
  display: inline-block;
  cursor: pointer;
  -webkit-transition: all 0.3s, padding 0s;
  transition: all 0.3s, padding 0s;
}

.header-all .header-all-right{
  margin-right: 50px;
  float: right;
  height: 100%;
  margin-left: auto;
  position: relative;
  transition: all 0.3s;
}
.headerAllRightStyle{
  background-color: rgba(0, 0, 0, 0.025);
}
.header-all .header-all-right .header-all-right-user{
  display: inline-block;
  height: 100%;
  padding: 0 12px;
  cursor: pointer;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
}
.header-all-right-swag{
  position: absolute;
  right: 0;
  width: 150px;
  top: 65px;
  background-color: white;
  transition: all 0.3s;
  box-shadow: 0 1px 4px #cccccc;
  z-index: 10;
}

.header-all-right-swag .swag-item{
  width: 100%;
  border: none;
  display: block;
  color: #333333;
  padding: 5px 0;
  margin: 5px 0;
}
.header-all-right-swag .swag-item:hover{
  background-color: #f0f5ff;
}
h2{
  line-height: 30px;
}
h3{
  line-height: 30px;
}
</style>
